import React, { useEffect, useState } from 'react';
import { 
  Table, 
  Card, 
  Button, 
  Input, 
  Select, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Upload, 
  Switch,
  Popconfirm,
  Image,
  Row,
  Col,
  Divider
} from 'antd';
import { useError } from '../../components/ui/ErrorHandler';
import { useLoading } from '../../components/ui/LoadingManager';
import { 
  PlusOutlined, 
  SearchOutlined, 
  EditOutlined, 
  DeleteOutlined,
  EyeOutlined,
  UploadOutlined,
  ExportOutlined,
  ImportOutlined,
  ReloadOutlined,
  TagsOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useProductStore } from '../../services/store';
import { useMessage } from '../../hooks/useMessage';
import { Loading } from '../../components/ui';
import { settingsApi } from '../../services/api';
import { useLocation } from 'react-router-dom';
import type { Product } from '../../types';


const { Search } = Input;
const { Option } = Select;
const { TextArea } = Input;

interface ProductFormData {
  name: string;
  description: string;
  type: string;
  category?: string;
  categoryId?: string;
  features: string[];
  images: string[];
  status: 'active' | 'inactive' | 'draft';
  sort: number;
  craftTypes: string[];
  specifications?: any;
}

const ProductManagePage: React.FC = () => {
  const [form] = Form.useForm();
  const location = useLocation();
  const message = useMessage();
  const { showError } = useError();
  const { withLoading } = useLoading();
  
  const { 
    products, 
    loading, 
    total, 
    fetchProducts, 
    createProduct, 
    updateProduct, 
    deleteProduct 
  } = useProductStore();
  
  const [modalOpen, setModalOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [productCategories, setProductCategories] = useState<string[]>([]);
  const [statusOptions] = useState<Array<{value: string, label: string}>>([  
    { value: 'active', label: '启用' },
    { value: 'inactive', label: '停用' },
    { value: 'draft', label: '草稿' }
  ]);
  const [categoryManageModalVisible, setCategoryManageModalVisible] = useState(false);
  const [newCategoryName, setNewCategoryName] = useState('');
  const [categoryLoading, setCategoryLoading] = useState(false);

  // 获取产品分类（简化为一级分类）
  const fetchProductCategories = async () => {
    try {
      const categories = await withLoading(
        settingsApi.getProductCategories(),
        '正在加载产品分类...'
      );
      // 直接使用返回的字符串数组
      setProductCategories(Array.isArray(categories) ? categories : ['门店招牌', '户外广告', '标识标牌', '室内装饰']);
    } catch (error: unknown) {
      console.error('获取产品分类失败:', error);
      showError(error instanceof Error ? error : '获取产品分类失败', {
        modal: false,
        details: '将使用默认分类'
      });
      setProductCategories(['门店招牌', '户外广告', '标识标牌', '室内装饰']);
    }
  };

  // 保存产品分类
  const saveProductCategories = async () => {
    try {
      setCategoryLoading(true);
      await withLoading(
        settingsApi.updateProductCategories(productCategories),
        '正在保存产品分类...'
      );
      message.success('产品分类保存成功');
      setCategoryManageModalVisible(false);
    } catch (error) {
      console.error('保存产品分类失败:', error);
      showError(error instanceof Error ? error : '保存产品分类失败', {
        modal: true,
        details: '请检查网络连接或稍后重试'
      });
    } finally {
      setCategoryLoading(false);
    }
  };

  // 添加分类
  const addLevel1Category = () => {
    if (!newCategoryName.trim()) {
      message.warning('请输入分类名称');
      return;
    }
    setProductCategories([...productCategories, newCategoryName.trim()]);
    setNewCategoryName('');
  };

  // 获取产品列表
  useEffect(() => {
    fetchProducts({
      page: currentPage,
      pageSize,
      keyword: searchKeyword,
      categoryId: selectedCategory === 'all' ? undefined : selectedCategory,
      status: selectedStatus === 'all' ? undefined : selectedStatus as 'active' | 'inactive' | 'draft'
    });
  }, [currentPage, pageSize, searchKeyword, selectedCategory, selectedStatus, fetchProducts]);

  // 初始化数据
  useEffect(() => {
    fetchProductCategories();
  }, []);



  // 检查从Dashboard传递的action参数
  useEffect(() => {
    if (location.state?.action === 'create') {
      handleAdd();
      // 清除state以避免重复触发
      window.history.replaceState({}, document.title);
    }
  }, [location.state]);

  // 搜索处理
  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setCurrentPage(1);
  };

  // 筛选处理
  const handleCategoryChange = (value: string) => {
    setSelectedCategory(value);
    setCurrentPage(1);
  };

  const handleStatusChange = (value: string) => {
    setSelectedStatus(value);
    setCurrentPage(1);
  };

  // 新增产品
  const handleAdd = () => {
    setEditingProduct(null);
    form.resetFields();
    form.setFieldsValue({
      status: 'active',
      sort: 0,
      features: [],
      images: [],
      craftTypes: [{
        name: '',
        price: '',
        unit: '平方米',
        description: '',
        specifications: {
          material: '',
          thickness: '',
          lightSource: '',
          installation: '',
          warranty: ''
        },
        features: [],
        images: [],
        isDefault: true
      }]
    });
    setModalOpen(true);
  };

  // 编辑产品
  const handleEdit = (product: Product) => {
    setEditingProduct(product);
    // 确保数据结构匹配新的表单结构
    const formData = {
      ...product,
      categoryId: product.categoryId,
      craftTypes: product.craftTypes || []
    };
    form.setFieldsValue(formData);
    setModalOpen(true);
  };

  // 删除产品
  const handleDelete = async (product: Product) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除产品"${product.name}"吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          await deleteProduct(product.id);
          message.success('产品已成功删除');
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : '删除产品时发生错误';
          message.error(errorMessage);
        }
      }
    });
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的产品');
      return;
    }

    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个产品吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          await Promise.all(
            selectedRowKeys.map(id => deleteProduct(id as string))
          );
          setSelectedRowKeys([]);
          message.success(`已成功删除 ${selectedRowKeys.length} 个产品`);
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : '批量删除时发生错误';
          message.error(errorMessage);
        }
      }
    });
  };

  // 刷新页面数据
  const handleRefresh = () => {
    fetchProducts({
      page: currentPage,
      pageSize,
      keyword: searchKeyword,
      categoryId: selectedCategory === 'all' ? undefined : selectedCategory,
      status: selectedStatus === 'all' ? undefined : selectedStatus as 'active' | 'inactive' | 'draft'
    });
    message.success('数据已刷新');
  };

  // 保存产品
  const handleSave = async (values: ProductFormData) => {
    try {
      if (editingProduct) {
        await updateProduct(editingProduct.id, values);
        message.success('产品信息已成功更新');
      } else {
        await createProduct(values);
        message.success('新产品已成功创建');
      }
      setModalOpen(false);
      form.resetFields();
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : '操作失败，请重试';
      message.error(errorMessage);
    }
  };

  // 快速切换状态
  const handleStatusToggle = async (product: Product) => {
    try {
      const newStatus = product.status === 'active' ? 'inactive' : 'active';
      await updateProduct(product.id, { ...product, status: newStatus });
      message.success(`产品已${newStatus === 'active' ? '启用' : '停用'}`);
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : '更新状态时发生错误';
      message.error(errorMessage);
    }
  };

  // 表格列定义
  const columns: ColumnsType<Product> = [
    {
      title: '产品图片',
      dataIndex: 'images',
      key: 'images',
      width: 120,
      render: (images: string[]) => (
        <Image
          width={80}
          height={60}
          src={images?.[0] || 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=product%20placeholder&image_size=square'}
          alt="产品图片"
          className="rounded object-cover"
          fallback=""
        />
      )
    },
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: true,
      sorter: true
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      render: (category: string) => {
        return (
          <Tag color="blue">
            {category || '未分类'}
          </Tag>
        );
      },
      filters: productCategories.map(cat => ({ text: cat, value: cat })),
      onFilter: (value, record) => record.categoryId === value || record.type === value
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string, record: Product) => (
        <Switch
          checked={status === 'active'}
          onChange={() => handleStatusToggle(record)}
          checkedChildren="启用"
          unCheckedChildren="停用"
        />
      ),
      filters: statusOptions.map(status => ({ text: status.label, value: status.value })),
      onFilter: (value, record) => record.status === value
    },

    {
      title: '排序',
      dataIndex: 'sortOrder',
      key: 'sortOrder',
      width: 80,
      sorter: true
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (date: string) => new Date(date).toLocaleDateString('zh-CN'),
      sorter: true
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record: Product) => (
        <Space size="small">
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => {
              // 预览功能
              message.info('预览功能开发中...');
            }}
          />
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          />
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          />
        </Space>
      )
    }
  ];

  return (
    <div className="p-6">
      <Card>
        {/* 页面标题和操作 */}
        <div className="flex justify-between items-center mb-6">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">产品管理</h1>
            <p className="text-gray-600 mt-1">管理所有产品信息</p>
          </div>
          <Space>
            <Button icon={<TagsOutlined />} onClick={() => setCategoryManageModalVisible(true)}>
              分类管理
            </Button>
            <Button icon={<ReloadOutlined />} onClick={handleRefresh}>
              刷新
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增产品
            </Button>
          </Space>
        </div>

        {/* 搜索和筛选 */}
        <Row gutter={[16, 16]} className="mb-4">
          <Col xs={24} sm={8} md={6}>
            <Search
              placeholder="搜索产品名称..."
              allowClear
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
            />
          </Col>
          <Col xs={12} sm={8} md={4}>
            <Select
              value={selectedCategory}
              onChange={handleCategoryChange}
              className="w-full"
              placeholder="选择分类"
            >
              <Option value="all">全部分类</Option>
              {productCategories.filter(category => category && category.trim()).map(category => (
                <Option key={category} value={category}>
                  {category}
                </Option>
              ))}
            </Select>
          </Col>
          <Col xs={12} sm={8} md={4}>
            <Select
              value={selectedStatus}
              onChange={handleStatusChange}
              className="w-full"
              placeholder="选择状态"
            >
              <Option value="all">全部状态</Option>
              {statusOptions.map((status, index) => (
                <Option key={`status-${status.value}-${index}`} value={status.value}>
                  {status.label}
                </Option>
              ))}
            </Select>
          </Col>
        </Row>

        {/* 批量操作 */}
        {selectedRowKeys.length > 0 && (
          <div className="mb-4 p-3 bg-blue-50 rounded">
            <Space>
              <span>已选择 {selectedRowKeys.length} 项</span>
              <Button size="small" onClick={() => setSelectedRowKeys([])}>
                取消选择
              </Button>
              <Button size="small" danger onClick={handleBatchDelete}>
                批量删除
              </Button>
            </Space>
          </div>
        )}

        {/* 产品表格 */}
        <Table
          columns={columns}
          dataSource={products}
          rowKey="id"
          loading={loading}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
            preserveSelectedRowKeys: true
          }}
          pagination={{
            current: currentPage,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size || 10);
            }
          }}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 产品编辑弹窗 */}
      <Modal
        title={editingProduct ? '编辑产品' : '新增产品'}
        open={modalOpen}
        onCancel={() => {
          setModalOpen(false);
          form.resetFields();
        }}
        footer={null}
        width={800}
        destroyOnHidden
        styles={{
          body: {
            maxHeight: '80vh',
            overflowY: 'auto',
            padding: '24px'
          }
        }}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
          autoComplete="off"
        >
          {/* 基础信息 Card */}
          <Card title="基础信息" className="mb-6">
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="name"
                  label="产品名称"
                  rules={[{ required: true, message: '请输入产品名称' }]}
                >
                  <Input placeholder="如：发光字、LED显示屏" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="type"
                  label="产品类型"
                  rules={[{ required: true, message: '请选择产品类型' }]}
                >
                  <Select placeholder="选择产品类型">
                    <Option value="标识导视">标识导视</Option>
                    <Option value="数字互动">数字互动</Option>
                    <Option value="品牌视觉设计">品牌视觉设计</Option>
                    <Option value="宣传印刷">宣传印刷</Option>
                    <Option value="包装制品">包装制品</Option>
                    <Option value="户外广告">户外广告</Option>
                    <Option value="展览展示">展览展示</Option>
                    <Option value="车体广告">车体广告</Option>
                    <Option value="党建文化">党建文化</Option>
                    <Option value="橱窗美陈">橱窗美陈</Option>
                    <Option value="光电标识">光电标识</Option>
                    <Option value="建筑装饰">建筑装饰</Option>
                    <Option value="背胶应用">背胶应用</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              name="description"
              label="产品描述"
              rules={[{ required: true, message: '请输入产品描述' }]}
            >
              <TextArea 
                rows={3} 
                placeholder="产品简介" 
                showCount 
                maxLength={500}
              />
            </Form.Item>

            <Form.Item
              name="features"
              label="产品特点"
            >
              <Select
                mode="tags"
                placeholder="添加产品特点"
                style={{ width: '100%' }}
              >
                <Option value="防水防尘">防水防尘</Option>
                <Option value="节能环保">节能环保</Option>
                <Option value="智能控制">智能控制</Option>
                <Option value="亮度可调">亮度可调</Option>
                <Option value="寿命长久">寿命长久</Option>
                <Option value="安装简便">安装简便</Option>
                <Option value="维护方便">维护方便</Option>
              </Select>
            </Form.Item>



            <Form.Item
              name="images"
              label="产品主图集"
            >
              <Upload
                listType="picture-card"
                multiple
                beforeUpload={() => false}
                fileList={[]}
                onChange={(info) => {
                  console.log('产品图片上传:', info);
                  // 这里应该处理图片上传逻辑
                }}
              >
                <div>
                  <UploadOutlined />
                  <div style={{ marginTop: 8 }}>上传图片</div>
                </div>
              </Upload>
            </Form.Item>
          </Card>

          {/* 工艺管理 Card */}
          <Card title="工艺管理" className="mb-6">
            <div className="text-sm text-gray-600 mb-4">
              一个产品可包含多种工艺，每种工艺有独立的价格、规格、图片等。如发光字产品可包含：无边发光字、迷你字、树脂字等工艺。
            </div>
            <Form.List name="craftTypes">
              {(fields, { add, remove }) => (
                <div className="space-y-4">
                  {fields.map(({ key, name, ...restField }, index) => (
                    <Card 
                      key={key} 
                      size="small" 
                      title={
                        <div className="flex justify-between items-center">
                          <span className="text-blue-600">
                            {index === 0 ? '默认工艺' : `工艺 ${index + 1}`}
                          </span>
                          {index > 0 && (
                            <Button 
                              type="link" 
                              danger 
                              size="small"
                              onClick={() => remove(name)}
                              icon={<DeleteOutlined />}
                            >
                              删除工艺
                            </Button>
                          )}
                        </div>
                      }
                      className="bg-gray-50"
                    >
                      <Row gutter={16}>
                        <Col span={12}>
                          <Form.Item
                            {...restField}
                            name={[name, 'name']}
                            label="工艺名称"
                            rules={[{ required: true, message: '请输入工艺名称' }]}
                          >
                            <Input placeholder="如：无边发光字" />
                          </Form.Item>
                        </Col>
                        <Col span={6}>
                          <Form.Item
                            {...restField}
                            name={[name, 'price']}
                            label="价格"
                            rules={[{ required: true, message: '请输入价格' }]}
                          >
                            <Input placeholder="280" addonAfter="元" />
                          </Form.Item>
                        </Col>
                        <Col span={6}>
                          <Form.Item
                            {...restField}
                            name={[name, 'unit']}
                            label="单位"
                            rules={[{ required: true, message: '请选择单位' }]}
                          >
                            <Select placeholder="选择单位" defaultValue="平方米">
                              <Option value="平方米">平方米</Option>
                              <Option value="米">米</Option>
                              <Option value="个">个</Option>
                              <Option value="套">套</Option>
                              <Option value="块">块</Option>
                              <Option value="张">张</Option>
                              <Option value="面">面</Option>
                            </Select>
                          </Form.Item>
                        </Col>
                      </Row>
                      
                      <Form.Item
                        {...restField}
                        name={[name, 'description']}
                        label="工艺描述"
                      >
                        <TextArea 
                          rows={2} 
                          placeholder="工艺特点和适用场景" 
                          showCount 
                          maxLength={200}
                        />
                      </Form.Item>
                      
                      {/* 技术规格 */}
                      <Form.Item label="技术规格">
                        <Row gutter={16}>
                          <Col span={8}>
                            <Form.Item
                              {...restField}
                              name={[name, 'specifications', 'material']}
                              label="材质"
                            >
                              <Input placeholder="如：亚克力+LED" />
                            </Form.Item>
                          </Col>
                          <Col span={8}>
                            <Form.Item
                              {...restField}
                              name={[name, 'specifications', 'thickness']}
                              label="厚度"
                            >
                              <Input placeholder="如：8-15mm" />
                            </Form.Item>
                          </Col>
                          <Col span={8}>
                            <Form.Item
                              {...restField}
                              name={[name, 'specifications', 'lightSource']}
                              label="光源"
                            >
                              <Input placeholder="如：LED灯带" />
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={16}>
                          <Col span={8}>
                            <Form.Item
                              {...restField}
                              name={[name, 'specifications', 'installation']}
                              label="安装方式"
                            >
                              <Input placeholder="如：墙面安装" />
                            </Form.Item>
                          </Col>
                          <Col span={8}>
                            <Form.Item
                              {...restField}
                              name={[name, 'specifications', 'warranty']}
                              label="质保期"
                            >
                              <Input placeholder="如：2年" />
                            </Form.Item>
                          </Col>
                          <Col span={8}>
                            <Form.Item
                              {...restField}
                              name={[name, 'isDefault']}
                              label="默认工艺"
                              valuePropName="checked"
                            >
                              <Switch 
                                checkedChildren="是" 
                                unCheckedChildren="否" 
                                disabled={index === 0}
                                defaultChecked={index === 0}
                              />
                            </Form.Item>
                          </Col>
                        </Row>
                      </Form.Item>
                      
                      <Form.Item
                        {...restField}
                        name={[name, 'features']}
                        label="工艺特点"
                      >
                        <Select
                          mode="tags"
                          placeholder="添加工艺特点"
                          style={{ width: '100%' }}
                        >
                          <Option value="防水防尘">防水防尘</Option>
                          <Option value="节能环保">节能环保</Option>
                          <Option value="亮度均匀">亮度均匀</Option>
                          <Option value="安装简便">安装简便</Option>
                          <Option value="维护方便">维护方便</Option>
                        </Select>
                      </Form.Item>
                      
                      <Form.Item
                        {...restField}
                        name={[name, 'images']}
                        label="工艺图片"
                      >
                        <Upload
                          listType="picture-card"
                          multiple
                          beforeUpload={() => false}
                          fileList={[]}
                          onChange={(info) => {
                            console.log('工艺图片上传:', info);
                            // 这里应该处理图片上传逻辑
                          }}
                        >
                          <div>
                            <UploadOutlined />
                            <div style={{ marginTop: 8 }}>上传图片</div>
                          </div>
                        </Upload>
                      </Form.Item>
                    </Card>
                  ))}
                  <Button 
                    type="dashed" 
                    onClick={() => add({ 
                      name: '', 
                      price: '', 
                      unit: '平方米', 
                      description: '',
                      specifications: {
                        material: '',
                        thickness: '',
                        lightSource: '',
                        installation: '',
                        warranty: ''
                      },
                      images: [],
                      features: [],
                      isDefault: false
                    })} 
                    block 
                    icon={<PlusOutlined />}
                    className="mt-4"
                  >
                    添加工艺
                  </Button>
                </div>
              )}
            </Form.List>
          </Card>



          {/* 发布设置 Card */}
          <Card title="发布设置" className="mb-6">
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="status"
                  label="发布状态"
                  rules={[{ required: true, message: '请选择发布状态' }]}
                >
                  <Select>
                    {statusOptions.map((status, index) => (
                      <Option key={`modal-status-${status.value}-${index}`} value={status.value}>
                        {status.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="sort"
                  label="排序权重"
                  help="数字越小越靠前，0表示按发布时间排序"
                >
                  <Input type="number" placeholder="0" min={0} />
                </Form.Item>
              </Col>
            </Row>
          </Card>

          <Divider />

          <div className="flex justify-end space-x-2">
            <Button onClick={() => setModalOpen(false)}>
              取消
            </Button>
            <Button type="primary" htmlType="submit" loading={loading}>
              {editingProduct ? '更新' : '创建'}
            </Button>
          </div>
        </Form>
      </Modal>

      {/* 产品分类管理模态框 */}
      <Modal
        title="产品分类管理"
        open={categoryManageModalVisible}
        onCancel={() => setCategoryManageModalVisible(false)}
        footer={null}
        width={600}
        destroyOnHidden
      >
        <div className="space-y-4">
          <div className="text-sm text-gray-600 mb-4">
            简化的产品分类管理：一级分类（如门店招牌、LED显示屏等），产品作为分类下的具体项目
          </div>
          
          {/* 添加分类 */}
          <div className="bg-gray-50 p-4 rounded-lg">
            <div className="flex items-center space-x-2 mb-4">
              <Input
                placeholder="输入分类名称"
                value={newCategoryName}
                onChange={(e) => setNewCategoryName(e.target.value)}
                style={{ width: 200 }}
              />
              <Button type="primary" onClick={addLevel1Category}>
                添加分类
              </Button>
            </div>
          </div>

          {/* 分类列表 */}
          <div className="space-y-2 max-h-96 overflow-y-auto">
            {productCategories.map((category, index) => (
              <div key={`category-${index}-${category}`} className="flex items-center justify-between p-3 border rounded-lg">
                <div className="flex items-center space-x-3">
                  <Tag color="blue">{category}</Tag>
                </div>
                <Button 
                  size="small" 
                  danger 
                  onClick={() => {
                    const updatedCategories = productCategories.filter((_, i) => i !== index);
                    setProductCategories(updatedCategories);
                  }}
                  icon={<DeleteOutlined />}
                >
                  删除
                </Button>
              </div>
            ))}
          </div>
          
          <div className="flex justify-end space-x-2 mt-4">
            <Button onClick={() => setCategoryManageModalVisible(false)}>
              关闭
            </Button>
            <Button type="primary" loading={categoryLoading} onClick={saveProductCategories}>
              保存更改
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default ProductManagePage;